package com.fileupload.upload.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 批量日志插入定时任务
 * 根据配置的策略（时间间隔）执行批量插入操作
 * @author 小乙
 */
@Component
public class BatchLogInsertTask {
    private static final Logger logger = LoggerFactory.getLogger(BatchLogInsertTask.class);

    @Autowired
    private BatchLogCollectorService batchLogCollectorService;
    
    @Autowired
    private BatchInsertConfig batchInsertConfig;

    /**
     * 定期执行批量插入的定时任务
     * 根据配置的时间间隔执行批量插入
     */
    @Scheduled(fixedRateString = "#{T(java.lang.Long).parseLong('${fileupload.batch.insert.interval-minutes:1}') * 60 * 1000}")
    public void scheduledBatchInsert() {
        // 检查批量插入功能是否启用
        if (!batchInsertConfig.isEnabled()) {
            logger.info("[定时任务] 批量插入功能已禁用，跳过定时任务执行");
            return;
        }
        
        int pendingCount = batchLogCollectorService.getPendingLogCount();
        int interval = batchInsertConfig.getIntervalMinutes();
        logger.info("[定时任务] 触发批量插入 - 配置间隔: {}分钟, 阈值: {}条, 当前待插入日志数量: {}", 
                interval, batchInsertConfig.getRecordThreshold(), pendingCount);
        
        if (pendingCount == 0) {
            logger.info("[定时任务] 当前没有待插入的日志记录，跳过插入操作");
            return;
        }
        
        long startTime = System.currentTimeMillis();
        try {
            logger.info("[定时任务] 开始执行批量插入操作 - 最大批量大小: {}, 重试次数: {}", 
                    batchInsertConfig.getMaxBatchSize(), batchInsertConfig.getMaxRetryCount());
            
            boolean result = batchLogCollectorService.executeBatchInsert();
            
            long duration = System.currentTimeMillis() - startTime;
            logger.info("[定时任务] 批量插入操作完成 - 执行结果: {}, 耗时: {}ms, 剩余待处理数量: {}", 
                    result ? "成功" : "失败", duration, batchLogCollectorService.getPendingLogCount());
        } catch (Exception e) {
            logger.error("[定时任务] 批量插入任务执行异常 - 错误信息: {}", e.getMessage(), e);
        }
    }
}